
#include <BChangeEvent>
#include <BFocusEvent>
#include <BFont>
#include <BStyle>
#include <BPainter>

#include <BMessageBox>
#include "member_BMessageBox.h"

using namespace BWE;

#define member					(*(member_BMessageBox*)_ptr)
#define member_allocate()		_ptr = new member_BMessageBox(this)
#define member_release()		delete (member_BMessageBox*)_ptr

BMessageBox::BMessageBox(BWidget* parent) : BDialog(parent)
{
	member_allocate();
	member.buttonLayout = new BHBoxLayout();
	this->setLayout(member.buttonLayout, Part_Bottom);
}
BMessageBox::~BMessageBox()
{

}

void BMessageBox::setText(const BString& text)
{
	if (member.text != text)
	{
		member.text = text;
		this->fresh();
	}
}
const BString& BMessageBox::text() const
{
	return member.text;
}

BSize BMessageBox::sizeHint() const
{
	return this->shellSize() + member.textSize + BSize(100, 100);
}

void BMessageBox::addButton(Button button)
{
	const char* text = member.buttonText(button);
	if (!text)
		return;
	BButton* btn = member.buttons.key(button);
	if (!btn)
	{
		btn = new BButton(text);
		member.buttons[btn] = button;
		member.buttonLayout->addWidget(btn);
		member.connect(btn, Signal_Clicked, &member_BMessageBox::procButtonClicked);
	}

}
bool BMessageBox::removeButton(Button button)
{
	BButton* btn = member.buttons.key(button);
	if (btn)
	{
		this->removeChild(btn);
		member.buttons.remove(btn);
		return true;
	}
	return false;
}
void BMessageBox::clearButtons()
{
	while (member.buttonLayout->count())
	{
		BWidget* widget = member.buttonLayout->widget(0);
		this->removeChild(widget);
	}
	member.buttons.clear();
}

void BMessageBox::changeEvent(const BChangeEvent& event)
{
	BDialog::changeEvent(event);
	if (event.change() == Change_Style)
	{
		const BStyle* style = event.style();
		const BFont* font = style->font();
		if (font)
		{
			member.textSize = font->textSize(member.text);
			this->setPerch(Part_Bottom, font->height() + 10);
		}
	}
}
void BMessageBox::freshEvent(const BEvent& event)
{
	BDialog::freshEvent(event);
	BRect crect = this->clientRect();
	member.textRect = crect.align(Align_Center, member.textSize);
}
void BMessageBox::paintEvent(const BEvent& event)
{
	BDialog::paintEvent(event);

	BPainter painter(this);
	painter.setColor(Color_Text);
	painter.drawText(member.textRect, member.text);
}

void BMessageBox::focusEvent(const BFocusEvent& event)
{
	if (event.focus() == Focus_Out)
	{
		if (this->modal() == false)
		{
			this->hide();
		}
	}
}
